package com.hzqy.commons.utils;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RegionalPricingUtil {
	private static final Log LOG = LogFactory.getLog(SignUtil.class);
	
	
	public static String getSign(Map<String,Object> signParams,String appSecret){
		//2.1 获取signParams中的key值
		StringBuilder sb = new StringBuilder();
		List<String> keyList = new ArrayList<String> (signParams.size());
		for (Map.Entry entry : signParams.entrySet()) {
			keyList.add((String) entry.getKey());
		}
		//2.2将key值进行排序
		Collections.sort(keyList);

		//2.3 按照该方式拼接成字符串 appSecret+key+map.get(key)+appSecret
		sb.append(appSecret);
		for (String key : keyList) {
			sb.append(key).append(signParams.get(key));
		}
		sb.append(appSecret);
		
		LOG.debug(sb.toString());
		//2.4 SHA1 加密后 将二进制输出为字符串
		try{
			byte[] sha1Digest = getSHA1Digest(sb.toString());
			return byte2hex(sha1Digest);
		} catch (IOException e) {
			LOG.debug("签名失败");
		}
		return "";
	}
	
	private static byte[] getSHA1Digest(String data) throws IOException {
		byte[] bytes = null;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			bytes = md.digest(data.getBytes("UTF-8"));
		} catch (GeneralSecurityException gse) {
			//throw new IOException(gse.getMessage());
		}
		return bytes;
		}

		private static String byte2hex(byte[] bytes){
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
			sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
		}
		
}
